import wtforms
from wtforms.validators import Email, Length, EqualTo, DataRequired, InputRequired
from models import Usermodel,EmailCaptureModel

# Form:主要验证前端提交的数据是否符合要求
class RegisterForm(wtforms.Form):
    email = wtforms.StringField(validators=[Email(message="邮箱格式错误"), DataRequired()])
    capture = wtforms.StringField(validators=[Length(min=4, max=4, message="验证码格式错误"), DataRequired()])
    username = wtforms.StringField(validators=[Length(min=3, max=10,message="用户名长度不符合要求"), DataRequired()])
    password = wtforms.StringField(validators=[Length(min=8, max=20,message="密码过长不符合要求"), DataRequired()])
    password_confirm = wtforms.StringField(validators=[EqualTo("password"), DataRequired()])

    # 自定义验证：
    # 验证邮箱是否被注册
    def validate_email(self, field):
        email = field.data
        user = Usermodel.query.filter_by(email=email).first()
        if user:
            # 手动设置异常
            raise wtforms.ValidationError(message='改邮箱已经被注册！')

    # 验证密码是否正确
    def validate_capture(self, field):
        capture = field.data
        email = self.email.data
        capture_model = EmailCaptureModel.query.filter_by(email=email,capture=capture).order_by(EmailCaptureModel.id).first()
        if not capture_model:
            raise wtforms.ValidationError(message="邮箱或者验证码错误！")

class LoginForm(wtforms.Form):
    email = wtforms.StringField(validators=[Email(message="请输入正确的邮箱！"),DataRequired()])
    password = wtforms.StringField(validators=[DataRequired(message="请输入密码！")])


class QuestionForm(wtforms.Form):
    title = wtforms.StringField(validators=[DataRequired()])
    content = wtforms.StringField(validators=[DataRequired()])

class AnswerForm(wtforms.Form):
    content = wtforms.StringField(validators=[DataRequired()])
    question_id = wtforms.IntegerField(validators=[InputRequired(message="必须要传入问题id")])

class SearchForm(wtforms.Form):
    q = wtforms.StringField(validators=[DataRequired()])